<!--
  智慧社区管理系统 - 请假申请页面
  严格按照《App端编码规范权威标准声明.md》中的填报规范实现
  使用u-datetime-picker原生日期选择器
  
  @author Wu.Liang
  @date 2025-01-30
  @description 请假申请功能，使用u-datetime-picker实现灵活的日期选择
-->
<template>
  <view class="page-container">
    <!-- 内容区域 -->
    <view class="content-section">
      <!-- 物业公司 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="home" color="#409eff" size="16"></u-icon>
          <text>物业公司</text>
          <text class="required">*</text>
        </view>
        <view class="select-wrapper" @click="showPropertyCompanyActionSheet">
          <text class="select-text">{{ formData.propertyCompanyName || '请选择物业公司' }}</text>
          <u-icon name="arrow-down" size="16" color="#999"></u-icon>
        </view>
      </view>

      <!-- 请假类型 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="list" color="#409eff" size="16"></u-icon>
          <text>请假类型</text>
          <text class="required">*</text>
        </view>
        <view class="select-wrapper" @click="showLeaveTypeActionSheet">
          <text class="select-text">{{ getLeaveTypeText(formData.leaveType) || '请选择请假类型' }}</text>
          <u-icon name="arrow-down" size="16" color="#999"></u-icon>
        </view>
      </view>

        <!-- 请假时间 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="calendar" color="#409eff" size="16"></u-icon>
            <text>请假时间</text>
            <text class="required">*</text>
          </view>
          <view class="date-range">
            <view class="date-item">
              <text class="date-label">开始日期</text>
              <view class="picker-display" @click="openStartDatePicker">
                <text class="picker-text">{{ formatDate(formData.startDate) || '请选择开始日期' }}</text>
                <u-icon name="calendar" color="#999" size="16"></u-icon>
              </view>
            </view>
            <text class="date-separator">至</text>
            <view class="date-item">
              <text class="date-label">结束日期</text>
              <view class="picker-display" @click="openEndDatePicker">
                <text class="picker-text">{{ formatDate(formData.endDate) || '请选择结束日期' }}</text>
                <u-icon name="calendar" color="#999" size="16"></u-icon>
              </view>
            </view>
          </view>
        </view>

      <!-- 请假天数 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="clock" color="#409eff" size="16"></u-icon>
          <text>请假天数</text>
          <text class="required">*</text>
        </view>
        <u-input 
          v-model="formData.days"
          placeholder="请输入请假天数"
          type="number"
          class="form-input"
          :disabled="true"
        />
        <text class="input-tip">系统将根据选择的日期自动计算</text>
      </view>

      <!-- 请假原因 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="edit-pen" color="#409eff" size="16"></u-icon>
          <text>请假原因</text>
          <text class="required">*</text>
        </view>
        <u-textarea 
          v-model="formData.reason"
          placeholder="请详细说明请假原因"
          :maxlength="200"
          :show-count="true"
          class="form-textarea"
        />
      </view>

      <!-- 紧急联系人 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="user" color="#409eff" size="16"></u-icon>
          <text>紧急联系人</text>
        </view>
        <u-input 
          v-model="formData.emergencyContact"
          placeholder="请输入紧急联系人姓名"
          class="form-input"
        />
      </view>

      <!-- 紧急联系电话 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="phone" color="#409eff" size="16"></u-icon>
          <text>紧急联系电话</text>
        </view>
        <u-input 
          v-model="formData.emergencyPhone"
          placeholder="请输入紧急联系电话"
          type="number"
          class="form-input"
        />
      </view>

      <!-- 相关附件 -->
      <view class="form-section">
        <view class="section-title">
          <u-icon name="folder" color="#409eff" size="16"></u-icon>
          <text>相关附件</text>
        </view>
        <AppImageUpload
          v-model="formData.attachments"
          title="上传相关证明文件"
          tip="支持jpg、jpeg、png、pdf格式，最大10MB"
          :max-count="5"
          :required="false"
          :max-size="10"
          :allowed-types="['jpg', 'jpeg', 'png', 'pdf']"
          upload-type="LEAVE_ATTACHMENT"
          upload-source="APP"
          @success="handleImageUploadSuccess"
          @error="handleImageUploadError"
        />
      </view>
    </view>

    <!-- 固定按钮区域 -->
    <view class="form-actions">
      <u-button 
        type="primary" 
        text="提交申请"
        size="large"
        @click="submitForm"
        :loading="submitting"
        :disabled="!canSubmit"
        class="submit-button"
      />
    </view>

    <!-- 使用uni.showActionSheet替代u-picker，确保有文字显示 -->
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import AppImageUpload from '@/components/AppImageUpload.vue'
import { submitLeaveApplication } from '@/api/leave'
import { getPropertyCompanySelectList } from '@/api/property'

export default {
  name: 'LeaveApply',
  components: {
    AppImageUpload
  },
  setup() {
    // 响应式数据
    const submitting = ref(false)
    const formData = reactive({
      propertyCompanyId: '', // 物业公司ID
      propertyCompanyName: '', // 物业公司名称
      leaveType: '',
      startDate: '', // 初始化为空字符串
      endDate: '',   // 初始化为空字符串
      days: '',
      reason: '',
      emergencyContact: '',
      emergencyPhone: '',
      attachments: []
    })

    // 物业公司列表
    const propertyCompanyList = ref([])


    // 生成日期选项数据 - 从今天开始到未来一年
    const generateDateOptions = () => {
      const options = []
      const today = new Date()
      const endDate = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000) // 一年后
      
      for (let d = new Date(today); d <= endDate; d.setDate(d.getDate() + 1)) {
        const dateStr = d.toISOString().split('T')[0]
        const label = `${d.getFullYear()}年${String(d.getMonth() + 1).padStart(2, '0')}月${String(d.getDate()).padStart(2, '0')}日`
        options.push({ label, value: dateStr })
      }
      
      return options
    }

    // 日期选项数据
    const staticDateOptions = generateDateOptions()


    // 请假类型选项
    const leaveTypeOptions = [
      { label: '事假', value: 'personal' },
      { label: '病假', value: 'sick' },
      { label: '年假', value: 'annual' },
      { label: '调休', value: 'compensatory' },
      { label: '产假', value: 'maternity' },
      { label: '陪产假', value: 'paternity' },
      { label: '其他', value: 'other' }
    ]

    // 计算属性
    const canSubmit = computed(() => {
      return formData.propertyCompanyId && 
             formData.leaveType && 
             formData.startDate && 
             formData.endDate && 
             formData.days && 
             formData.reason
    })

    // 获取请假类型显示文本
    const getLeaveTypeText = (value) => {
      const option = leaveTypeOptions.find(item => item.value === value)
      return option ? option.label : ''
    }

    // 显示物业公司选择ActionSheet
    const showPropertyCompanyActionSheet = () => {
      if (propertyCompanyList.value.length === 0) {
        uni.showToast({
          title: '物业公司列表为空',
          icon: 'none'
        })
        return
      }
      
      const itemList = propertyCompanyList.value.map(item => item.companyName)
      uni.showActionSheet({
        itemList,
        success: (res) => {
          const selectedCompany = propertyCompanyList.value[res.tapIndex]
          formData.propertyCompanyId = selectedCompany.id
          formData.propertyCompanyName = selectedCompany.companyName
          console.log('选择物业公司:', selectedCompany)
        }
      })
    }

    // 显示请假类型选择ActionSheet
    const showLeaveTypeActionSheet = () => {
      const itemList = leaveTypeOptions.map(item => item.label)
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          const selectedOption = leaveTypeOptions[res.tapIndex]
          formData.leaveType = selectedOption.value
          console.log('选择请假类型:', selectedOption)
        }
      })
    }

    // 打开开始日期选择器 - 使用uni.showActionSheet
    const openStartDatePicker = () => {
      const dateList = staticDateOptions.map(item => item.label)
      uni.showActionSheet({
        itemList: dateList,
        success: (res) => {
          const selectedDate = staticDateOptions[res.tapIndex]
          formData.startDate = selectedDate.value
          console.log('选择开始日期:', selectedDate)
          
          // 如果结束日期早于开始日期，清空结束日期
          if (formData.endDate && formData.endDate < formData.startDate) {
            formData.endDate = ''
            formData.days = ''
          }
          
          // 重新计算请假天数
          calculateDays()
        }
      })
    }

    // 打开结束日期选择器 - 使用uni.showActionSheet
    const openEndDatePicker = () => {
      if (!formData.startDate) {
        uni.showToast({
          title: '请先选择开始日期',
          icon: 'none'
        })
        return
      }
      
      // 生成结束日期选项 - 从开始日期开始到未来一年
      const generateEndDateOptions = () => {
        const options = []
        const startDate = new Date(formData.startDate)
        const endDate = new Date(startDate.getTime() + 365 * 24 * 60 * 60 * 1000) // 开始日期后一年
        
        for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
          const dateStr = d.toISOString().split('T')[0]
          const label = `${d.getFullYear()}年${String(d.getMonth() + 1).padStart(2, '0')}月${String(d.getDate()).padStart(2, '0')}日`
          options.push({ label, value: dateStr })
        }
        
        return options
      }
      
      const endDateOptions = generateEndDateOptions()
      const dateList = endDateOptions.map(item => item.label)
      
      uni.showActionSheet({
        itemList: dateList,
        success: (res) => {
          const selectedDate = endDateOptions[res.tapIndex]
          formData.endDate = selectedDate.value
          console.log('选择结束日期:', selectedDate)
          
          // 重新计算请假天数
          calculateDays()
        }
      })
    }


    // 计算请假天数
    const calculateDays = () => {
      if (!formData.startDate || !formData.endDate) {
        formData.days = ''
        return
      }
      
      // 处理字符串格式的日期
      const startDate = new Date(formData.startDate)
      const endDate = new Date(formData.endDate)
      
      if (endDate < startDate) {
        uni.showToast({
          title: '结束日期不能早于开始日期',
          icon: 'none'
        })
        formData.endDate = ''
        formData.days = ''
        return
      }
      
      const timeDiff = endDate.getTime() - startDate.getTime()
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1 // +1 包含开始日期
      
      formData.days = daysDiff.toString()
      console.log('计算请假天数:', daysDiff)
    }

    // 格式化日期显示
    const formatDate = (date) => {
      if (!date) return ''
      // 处理字符串格式的日期
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    }

    // 图片上传成功处理
    const handleImageUploadSuccess = (data) => {
      console.log('图片上传成功:', data)
      uni.showToast({
        title: '上传成功',
        icon: 'success'
      })
    }

    // 图片上传错误处理
    const handleImageUploadError = (error) => {
      console.error('图片上传失败:', error)
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'error'
      })
    }

    // 提交表单
    const submitForm = async () => {
      if (!canSubmit.value) {
        uni.showToast({
          title: '请填写必填项',
          icon: 'none'
        })
        return
      }

      try {
        submitting.value = true

        // 获取当前用户ID - 从本地存储或用户信息中获取
        const userInfo = uni.getStorageSync('userInfo')
        const userId = userInfo?.id || userInfo?.userId
        
        if (!userId) {
          uni.showToast({
            title: '用户信息获取失败，请重新登录',
            icon: 'none'
          })
          return
        }

        // 处理附件数据 - 转换为JSON格式
        let attachmentsJson = null
        if (formData.attachments && formData.attachments.length > 0) {
          try {
            // 将AppImageUpload组件返回的文件信息转换为JSON字符串
            attachmentsJson = JSON.stringify(formData.attachments)
            console.log('附件数据转换为JSON:', attachmentsJson)
          } catch (error) {
            console.error('附件数据转换失败:', error)
            uni.showToast({
              title: '附件数据处理失败',
              icon: 'none'
            })
            return
          }
        }

        const submitData = {
          userId: userId,
          propertyCompanyId: formData.propertyCompanyId,
          leaveType: formData.leaveType,
          startDate: formatDate(formData.startDate),
          endDate: formatDate(formData.endDate),
          days: parseInt(formData.days),
          reason: formData.reason.trim(),
          emergencyContact: formData.emergencyContact.trim(),
          emergencyPhone: formData.emergencyPhone.trim(),
          attachments: attachmentsJson
        }

        console.log('提交数据:', submitData)

        // 调用后端API提交请假申请
        const result = await submitLeaveApplication(submitData)
        
        if (result.success) {
          uni.showToast({
            title: result.message || '提交成功',
            icon: 'success'
          })

          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: result.message || '提交失败，请重试',
            icon: 'none'
          })
        }

      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'error'
        })
      } finally {
        submitting.value = false
      }
    }

    // 加载物业公司列表
    const loadPropertyCompanyList = async () => {
      try {
        console.log('开始加载物业公司列表')
        const result = await getPropertyCompanySelectList()
        
        if (result.success && result.data) {
          propertyCompanyList.value = result.data
          console.log('物业公司列表加载成功:', result.data)
          
          // 默认选择第一个物业公司
          if (result.data.length > 0) {
            const firstCompany = result.data[0]
            formData.propertyCompanyId = firstCompany.id
            formData.propertyCompanyName = firstCompany.companyName
            console.log('默认选择物业公司:', firstCompany)
          }
        } else {
          console.error('物业公司列表加载失败:', result.message)
          uni.showToast({
            title: result.message || '加载物业公司列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载物业公司列表异常:', error)
        uni.showToast({
          title: '加载物业公司列表失败',
          icon: 'none'
        })
      }
    }

    // 页面初始化
    onMounted(() => {
      // 加载物业公司列表
      loadPropertyCompanyList()
      
      // 设置默认开始日期为今天
      formData.startDate = new Date().toISOString().split('T')[0]
      
      // 设置默认结束日期为开始日期后7天
      const defaultEndDate = new Date()
      defaultEndDate.setDate(defaultEndDate.getDate() + 7)
      formData.endDate = defaultEndDate.toISOString().split('T')[0]
      
      // 计算默认请假天数
      calculateDays()
    })

    return {
      submitting,
      formData,
      propertyCompanyList,
      canSubmit,
      getLeaveTypeText,
      showPropertyCompanyActionSheet,
      showLeaveTypeActionSheet,
      openStartDatePicker,
      openEndDatePicker,
      formatDate,
      handleImageUploadSuccess,
      handleImageUploadError,
      submitForm
    }
  }
}
</script>

<style lang="scss" scoped>
/* 页面容器 - 必须完全顶满手机宽度 */
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 内容区域 - 确保无左右空白 */
.content-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  flex: 1;
}

/* 表单区块 - 统一的间距和样式 */
.form-section {
  margin-bottom: 24px;
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 15px;
    font-weight: 600;
    color: #333;
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

/* 选择器样式 */
.select-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  min-height: 44px;
  cursor: pointer;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
  
  &:active {
    background-color: #e9ecef;
    transform: scale(0.98);
  }
}

.select-text {
  flex: 1;
  font-size: 14px;
  color: #333;
  text-align: left;
}

.select-text:empty::before {
  content: '请选择';
  color: #999;
}

/* 日期范围样式 */
.date-range {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  
  .date-item {
    flex: 1;
    
    .date-label {
      display: block;
      font-size: 12px;
      color: #666;
      margin-bottom: 8px;
    }
  }
  
  .date-separator {
    font-size: 14px;
    color: #666;
    font-weight: 500;
    margin-top: 24px;
  }
}

/* 日期选择器显示样式 */
.picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  min-height: 44px;
  cursor: pointer;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
  
  &:active {
    background-color: #e9ecef;
    transform: scale(0.98);
  }
}

.picker-text {
  flex: 1;
  font-size: 14px;
  color: #333;
  text-align: left;
}

/* 表单输入框样式 */
.form-input {
  width: 100%;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
}

.form-textarea {
  width: 100%;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  min-height: 100px;
}

/* 输入提示样式 */
.input-tip {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 固定按钮区域 */
.form-actions {
  flex-shrink: 0;
  padding: 16px;
  background: white;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  
  .submit-button {
    width: 100%;
    height: 48px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .content-section {
    padding: 12px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
  
  .date-range {
    flex-direction: column;
    gap: 8px;
    
    .date-separator {
      display: none;
    }
  }
}

@media screen and (min-width: 414px) {
  .content-section {
    padding: 20px;
  }
}
</style>